<?php
class UserPrivateModel extends BaseModel
{
    protected $table = 'user_private';

    // 通过uid 和 基金id查找用户预约状态
    public static function findByUidAndPid($uid, $pid)
    {
        /** @var self $result */
        $result = self::query()->where(['uid' => $uid, 'pid' => $pid])
            ->first();

        return $result;
    }

    public static function create($uid, $pid)
    {
        $data = array(
            'uid' => $uid,
            'pid' => $pid,
            'update_time' => date('Y-m-d H:i:s'),
            'create_time' => date('Y-m-d H:i:s'),
        );
        $model = new self();
        $model->fill($data);
        $model->save();

        return $model;
    }

    /**
     * @param $uid
     * @param $pid
     * @return UserPrivateModel
     */
    public static function findOrCreate($uid, $pid)
    {
        return self::findByUidAndPid($uid, $pid)?: self::create($uid, $pid);
    }

    // 20次认证失败后，次日将状态重置为初始
    public function clearFailStatus($failtime)
    {
        if ($failtime < 20 && $this->private_reserve_status == 5) {
            self::query()->where(['id' => $this->id, 'private_reserve_status' => 5])
                ->update(['private_reserve_status' => 1]);
            $this->private_reserve_status = 1;
            $this->save();
        }
    }

    //是否处于人工审核中
    public function isManualChecking()
    {
        return $this->private_reserve_status == 3 ? 1 : 0;
    }

    // 人工审核通过后直接展示风险揭示页面
    public function showRiskTipDirectly()
    {
        if ($this->private_reserve_status == 6) { // 认证通过
            if ($last = UserVerifaceRecordModel::getLastPassReocrd($this->uid, $this->pid)) {
                if ($last->manual_pass) { // 人工审批通过的
                    return 1;
                }
            }
        }

        return 0;
    }

    /**
     * 用户在风险揭示页面点击了确定/取消按钮
     * @param $accept int
     * @return int
     */
    public function accept($accept)
    {
        if ($accept == 1) {
            $status = 4;
        } else {
            $status = 1;
        }
        return self::query()->where(['id' => $this->id, 'private_reserve_status' => 6 ])
            ->update(['private_reserve_status' => $status]);
    }

    public function isOk()
    {
        return in_array($this->private_reserve_status, [4]);
    }
}
